<template>
  <el-form ref="deptForm" :model="form" :rules="formRules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option
          v-for="item in list"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input
        v-model="form.introduce"
        style="width:80%"
        placeholder="1-300个字符"
        type="textarea"
        :rows="3"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeesSimples } from "@/api/employees";
import { addDepartments,getDepartmentsDetail,updateDepartment } from '@/api/departments';
export default {
  props:{
    id:{
      type:String,
      required:true
    },
    isEdit:{
      type:Boolean,
      required:true
    },
    originList:{
      type:Array,
      required:true
    }
  },
  data() {
    // 定义一个校验规则函数 校验部门的编码唯一性
    const validCode=(rule,value,callback)=>{
      //获取整个部门的编码  编码的数组
      console.log('this.originList',this.originList);
      let exisCodeList=this.originList.map(item=> item.code)
      console.log('exisCodeList',exisCodeList);

      // 如果是编辑的状态，将当前编辑的部门的编码从存在的数组中移除
      if (this.isEdit) {
        exisCodeList= this.originList.filter(item=>item.id!==this.id).map(item=>item.code)
      }
      //判断当前的value是否在数组中存在
      if (exisCodeList.includes(value)) {
        callback(new Error(`该部门编码${value}已存在`))
      }else{
        callback()
      }
    }

    // 定义一个校验规则函数  部门名称同级不能重复(父级部门的id等于子部门的pid)
    const validName=(rule,value,callback)=>{
      let existNameList=this.originList.filter(item=>item.pid===this.id).map(item=>item.name)
      console.log('部门ex',existNameList);

      // 如果是编辑
      if (this.isEdit) {
        //获取当前选中部门的id，再获取pid，再获取同级部门的pid，再去除自己，留下同级部门的pid
        const pid=this.originList.find(item=>item.id===this.id).pid
        console.log('pid',pid);
        const brothers=this.originList.filter(item=>item.pid===pid)
         existNameList=brothers.filter(item=>item.id!==this.id).map(item=>item.name)
      } 
      if (existNameList.includes(value)) {
        callback(new Error(`该部门名称${value}已经存在`))
      } else {
        callback()
      }
    }
    return {
      list: [], //存储部门负责人列表
      form: {
        name: "",
        code: "",
        manager: "",
        introduce: ""
      },
      // 验证规则对象
      formRules:{
        name:[
          {required:true,message:'请输入部门名称',trigger:'blur'},
          {min:1,max:50,message:'请输入1~50的部门编码',trigger:'blur'},
          {validator:validName,trigger:'blur'}
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1~50的部门编码', trigger: 'blur' },
          {validator:validCode,trigger:'blur'}
        ],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入1~300的部门编码', trigger: 'blur' }
        ]
      }
    };
  },
  watch:{
    id:function(new_val,old_val){
      console.log('new_val',new_val);
      console.log('old_val',old_val);
      this.loadDepartmentDetail()
    }
  },
  created() {
    this.laodEmployeesSimples();
    //只有是编辑操作才有需要请求详情数据
    // if (this.isEdit) {
    //   this.loadDepartmentDetail()
    // }
  },
  methods: {
    //在子组件定义充值表单的方法
    resetForm(){
      this.$refs.deptForm.resetFields()
    },
    // 实现编辑部门
    async doEdit(){
      try {
        // console.log('123');
        await updateDepartment(this.form)
        console.log('updateDepartment(this.form)',updateDepartment(this.form));
        this.$emit('success')
      } catch (error) {
        console.log(error);
      }
    },
    //加载部门详情数据，填充到表单中
    async loadDepartmentDetail(){
      try {
        console.log('执行了created');
        const res=await getDepartmentsDetail(this.id)
        console.log('getDepartmentsDetail',res);
        this.form=res.data
        console.log('form',res.data);
      } catch (error) {
        console.log(error);
      }
    },
    // 实现添加子部门
    async doAdd(){
      try {
        //pid:this.id作为子部门的pid
        const res= await addDepartments({pid:this.id,...this.form})
        console.log('addDepartment',res);
        //子传父关闭弹层，重新渲染数据
        this.$emit('success')
      } catch (error) {
        console.log(error);
      }
    },
    // 获取部门负责人列表
    async laodEmployeesSimples() {
      try {
        const res = await getEmployeesSimples();
        console.log("getEmployeesSimples", res);
        this.list = res.data;
      } catch (error) {
        console.log(error);
      }
    },
    hSubmit() {
      this.$refs.deptForm.validate(valid =>{
        if(!valid) return
        // 实现编辑 或者 新增
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    hCancel() {
      this.$emit('close')
    }
  }
};
</script>

<style scoped>
</style>